<template>
  <div class="bread">
    <!-- 大屏模式只展现一条面包屑 -->
    <el-breadcrumb v-if="bigScreen" :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/sys/role' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item v-for="item in breadArr" :key="item.id">{{
        item.name
      }}</el-breadcrumb-item>
    </el-breadcrumb>

    <el-breadcrumb v-else :separator-icon="ArrowRight">
      <el-breadcrumb-item>{{ breadArr[breadArr.length-1].name }}</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script setup lang="ts">
import { ArrowRight } from "@element-plus/icons-vue"
import { useRoute } from "vue-router"
import { ref, watch } from "vue"
import menus from "@/stores/menus"
import usePageInfo from "@/stores/pageInfo"
import { storeToRefs } from "pinia"

const route = useRoute()
const menusStore = menus()
// 获取此时是大屏还是小屏模式
const { bigScreen } = storeToRefs(usePageInfo())

// 存储面包屑数组
const breadArr = ref<menusType[]>([])

// 监听route
watch(
  route,
  (value) => {
    getMenus()
  },
  {
    immediate: true
  }
)

// 通过循环获取所有父路由(因为所有的子菜单都是同级地的)
function getMenus() {
  // 调用后数组清空
  breadArr.value = []

  // 获取当前路由地址对应的菜单对象
  let menu = menusStore.menus.find((res) => {
    return res.router === route.path
  })

  if (!menu) return

  // 使用当前路由找到所有子菜单
  while (menu) {
    if (!menu) return
    breadArr.value.unshift(menu)
    menu = menusStore.menus.find((res) => {
      return menu?.parentId === res.id + ""
    })
  }
}
</script>

<style scoped lang="scss">
.bread {
  margin-left: 10px;
}
</style>
